<template>
  <div class="app-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-width="120px" label-position="right">
      <el-form-item label="用户名" prop="user_name">
        <el-input v-model.trim="postForm.user_name" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="密码" prop="user_password">
        <el-input v-model="postForm.user_password" type="password" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="真实姓名" prop="realname">
        <el-input v-model.trim="postForm.realname" style="width: 300px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getUserInfo, saveUser } from '@/api/admin'

export default {
  name: 'Index',
  data() {
    const checkPassword = (rules, value, callback) => {
      if (value == '') { // 未作改动
        callback()
      } else if (value.length <= 4) {
        console.log(value)
        callback(new Error('密码长度不小于5位'))
      } else {
        callback()
      }
    }
    return {
      postForm: {
        user_name: '',
        user_password: '',
        realname: ''
      },
      rules: {
        user_name: [{ required: true, message: '用户名不能为空', trigger: 'change' }],
        user_password: [{ validator: checkPassword, trigger: 'change' }],
        realname: [{ required: true, message: '真实姓名不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getUserInfo().then(res => {
        this.postForm.user_name = res.data.user_name
        this.postForm.realname = res.data.realname
      })
      this.$nextTick(() => {
        this.$refs['postForm'].clearValidate()
      })
    },
    onSubmit() {
      // 密码不能用空格做密码
      if (this.postForm.user_password.length > 0 && this.postForm.user_password.trim() == '') {
        this.$message.error('不能使用空格做密码')
        return
      }
      this.$refs['postForm'].validate(valid => {
        if (valid) {
          saveUser(this.postForm).then(res => {
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          }).catch(() => {})
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
